<?php

// 	說明文件
//		Elasticsearch-PHP
//			https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html
//		Elasticsearch 权威指南（中文版）
//			https://es.xiaoleilu.com/index.html
//		Elasticsearch Reference
//		https://www.elastic.co/guide/en/elasticsearch/reference/5.4/index.html

// 	使用此class必須先做以下事項
//		config.php
//			ES_ 等常數
//		composer.json
//			"elasticsearch/elasticsearch": "~5.2",
//			"jsq/amazon-es-php": "~0.2"

/**
	備註
		刪除index
			$client->indices()->delete(array('index'=>$index_name));

		取出index100筆資料
			$params = [
				'index' => 'member_school_index',
				'type' => 'school_type',
				'body' => '{
					"from" : 0, 
					"size" : 100,
					"query" : {
						"match_all" : {}
					}
				}'
			];

			$schools = $client->search($params);
*/

namespace FS\Library;

use \Aws\Credentials\CredentialProvider;
use \Aws\Credentials\Credentials;
use \Aws\ElasticsearchService\ElasticsearchPhpHandler;
use \Elasticsearch\ClientBuilder;


class ElasticSearch { 

	// 
	// -------------------------------------------------------------------------
    function get_client() {

		include_once LIBRARY_PATH.'/autoload.php';

		// 用第三方的library跟 amazon elasticsearch service 溝通 
		// https://github.com/jeskew/amazon-es-php

		$provider = CredentialProvider::fromCredentials( new Credentials(ES_KEY, ES_SECRET) );
		$handler = new ElasticsearchPhpHandler(ES_REGION, $provider);
		return ClientBuilder::create()->setHandler($handler)->setHosts([ES_WWW])->build();

    }

	// 批次加入document
	// -----------------------------------------------------------------
	public function create_many_document( $client, $index, $type, $insert_array ){

		// $insert_array 裡的每一筆必須要有id欄位

		// $insert_array 資料格式如下
		// array(
		//		array( 'id' => 1, 'name' => 'test'),
		//		array( 'id' => 2, 'name' => 'abc')
		// )
		
		$params['index'] = $index;
		$params['type']  = $type;

		// 迴圈要加入的所有資料
		foreach ($insert_array as $row) {

			$document_head = array();
			$document = array();

			// 取出所有欄位名稱
		    foreach( array_keys($row) as $column ){

		    	// 另外設定其中的欄位名稱id
		    	if( $column == 'id' ){

				    $document_head['index']['_id'] = $row['id'];

				// 將資料放進相對應的document欄位
		    	}else{
		    		$document[$column] = $row[$column];
		    	}

		    }

		    $params['body'][] = $document_head;
		    $params['body'][] = $document;
		}

		$client->bulk($params);
	}
}

